<template>
  <el-form
    ref="paramsForm"
    :model="form"
    class="form-fixed"
    label-width="20%"
    label-suffix="："
    @submit.native.prevent
  >
    <el-form-item
      label="参数模板"
      prop="tid"
    >
      <el-select
        v-model="form.tid"
        clearable
        placeholder="请选择参数模板"
      >
        <el-option
          v-for="item in paramTemplates"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-table
        ref="multipleParamsTable"
        :data="form.params"
        border
        style="width:80%"
      >
        <el-table-column
          label="参数名"
          min-width="30%"
        >
          <template slot-scope="scope">
            <el-form-item v-if="!scope.row.template_id">
              <el-form-item
                :rules="rules.fieldName"
                :prop="`params[${scope.$index}].name`"
              >
                <el-input
                  :ref="`formInput.params[${scope.$index}].name`"
                  v-model="scope.row.name"
                  placeholder="请输入参数名"
                />
              </el-form-item>
            </el-form-item>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="参数值"
          prop="values"
        >
          <template slot-scope="scope">
            <el-form-item :prop="`params[${scope.$index}].value`">
              <el-input
                v-if="scope.row.inputType==='text'"
                v-model="scope.row.value"
                placeholder="请输入参数值"
              />
              <el-radio-group
                v-else-if="scope.row.inputType==='radio'"
                v-model="scope.row.value"
              >
                <el-radio
                  v-for="(item,index) in scope.row.options"
                  :key="index"
                  :label="item.value"
                >{{ item.value }}</el-radio>
              </el-radio-group>
              <el-checkbox-group
                v-else-if="scope.row.inputType==='checkbox'"
                v-model="scope.row.value"
              >
                <el-checkbox
                  v-for="(item,index) in scope.row.options"
                  :key="index"
                  :label="item.value"
                />
              </el-checkbox-group>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="排序"
          prop="listorder"
          width="100px"
          align="center"
        >
          <template slot-scope="scope">
            <el-form-item>
              <number-input
                v-model="scope.row.listorder"
                :step="1"
                :min="0"
                step-strictly
                align="center"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="100px"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="onDelete(scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pt-4">
        <el-button @click="onAddParams">添加参数</el-button>
      </div>
    </el-form-item>
    <fixed-box>
      <el-form-item>
        <div>
          <el-button
            type="primary"
            @click="onSubmit"
          >提交保存</el-button>
        </div>
        <div>
          <slot name="steps" />
          <el-button @click="goBack">返回</el-button>
        </div>
      </el-form-item>
    </fixed-box>
  </el-form>
</template>

<script>
import NumberInput from '@/components/Form/NumberInput'
import FixedBox from '@/layout/components/FixedBox'
export default {
  name: 'GoodsParamsForm',
  components: {
    NumberInput,
    FixedBox
  },
  inject: ['goBack'],
  props: {
    value: {
      type: [Number, String],
      default: 0
    },
    step: {
      type: Number,
      default: 0
    },
    steps: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      rules: {
        fieldName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      form: {
        tid: null,
        params: []
      },
      tableBodyList: [],
      tempParams: [],
      metaParams: [],
      customParams: [],
      paramTemplates: []
    }
  },
  computed: {
    activeTemplate() {
      if (this.form.tid) {
        return this.paramTemplates.find(item => {
          return item.id === this.form.tid
        })
      }
      return null
    },
    activeParams() {
      if (this.activeTemplate) {
        var params = this.activeTemplate.params.map(item => {
          var tempItem = this.metaParams.find(mi => {
            return mi.field_id === item.field_id
          })
          return Object.assign(item, tempItem || {})
        })
        console.log(params)
        return params
          .concat(this.customParams)
          .concat(this.tempParams)
          .sort((a, b) => {
            return a.listorder - b.listorder
          })
      } else {
        return this.metaParams.concat(this.tempParams)
      }
    }
  },
  watch: {
    form: {
      handler(v) {
        console.log('form is changed:', v)
      },
      deep: true
    },
    activeParams: {
      handler(v) {
        console.log('activeParams is changed:', v)
        this.tableBodyList = [].concat(v)
        // this.tableBodyList = JSON.parse(JSON.stringify(v))
      },
      deep: true
    },
    tableBodyList: {
      handler(v) {
        console.log('tableBodyList is changed:', v)
        // var params = JSON.parse(JSON.stringify(v))
        // params.sort((a, b) => {
        //   return a.listorder - b.listorder
        // })
        this.form.params = JSON.parse(JSON.stringify(v))
      },
      deep: true
    }
  },
  created() {
    this.onLoadParams()
  },
  mounted() {},
  methods: {
    onLoadParams() {
      this.$http.commodity.paramsConfig(this.value).then(res => {
        console.log(res.data)
        this.onMountData(res.data)
      })
    },
    onAddParams() {
      this.form.params.push({
        id: 0,
        name: '',
        template_id: 0,
        field_id: 0,
        inputType: 'text',
        options: [],
        value: '',
        listorder: 0
      })
    },
    onDelete(index) {
      this.form.params.splice(index, 1)
    },
    onMountData(data) {
      console.log(data)
      const { form, templates } = data
      this.form = { ...form }
      if (templates && templates.length > 0) {
        this.paramTemplates = templates
      }
      if (this.form.params && this.form.params.length) {
        this.customParams = this.form.params.filter(item => {
          return !item.template_id
        })
        this.metaParams = this.form.params.map(item => {
          return item
        })
      }
    },
    onSubmit() {
      this.$refs.paramsForm.validate((valid, obj) => {
        if (valid) {
          var validateParams = this.form.params.filter(item => {
            return item.value && item.value.length > 0
          })
          var message = ''
          var confirmOptions = {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            showConfirmButton: true
          }
          if (!this.form.params.length) {
            console.log(this.metaParams)
            if (this.metaParams.length) {
              message = '是否清空已保存的参数, 确认清空参数?'
            } else {
              message = '没有设置商品参数内容，不需要提交保存。'
              confirmOptions.showConfirmButton = true
              confirmOptions.cancelButtonText = '关闭'
            }
          } else if (validateParams.length !== this.form.params.length) {
            message =
              '提交的参数中含有未选择参数值的参数，未选择参数值部分的参数将不会保存, 是否继续提交?'
          }
          var data = {
            tid: this.form.tid,
            params: validateParams.sort((a, b) => {
              return a.listorder - b.listorder
            })
          }
          if (message) {
            this.$confirm(message, '提示', confirmOptions)
              .then(() => {
                this.submit(data)
              })
              .catch(() => {
                console.log('cancelled')
              })
          } else {
            this.submit(data)
          }
        } else {
          console.log(obj)
          let firstErrorElname = ''
          for (const i in obj) {
            firstErrorElname = `formInput.${i}`
            console.log(firstErrorElname)
            break
          }
          var dom = this.$refs[firstErrorElname]
          console.log(dom, this.$refs)
          if (dom) {
            dom.$refs.input && dom.$refs.input.focus()
            dom.$el.scrollIntoView({
              // 滚动到指定节点
              block: 'center', // 值有start,center,end，nearest，当前显示在视图区域中间
              behavior: 'smooth' // 值有auto、instant,smooth，缓动动画（当前是慢速的）
            })
          }
          console.log('error submit!!', this.form)
          return false
        }
      })
    },
    submit(data) {
      console.log('submit data', data)
      this.$http.commodity.updateParams(data, this.value).then(res => {
        console.log(res.data)
        // this.onLoadParams()
        this.$emit('saved', res.data)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.params-actionbox {
  padding: 10px;
}
</style>
